package cn.sylinx.redis.springboot.starter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import cn.sylinx.common.ext.log.GLog;
import cn.sylinx.redis.springboot.BaseRedisCommand;
import cn.sylinx.redis.springboot.JedisPoolResource;
import cn.sylinx.redis.springboot.RedisConfig;
import cn.sylinx.redis.springboot.SpringJedisPoolFactoryBean;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.util.Pool;

@Configuration
@EnableConfigurationProperties(RedisConfig.class)
@ConditionalOnClass(BaseRedisCommand.class)
@ConditionalOnProperty(prefix = "redis.cfg", value = "inited")
public class RedisStarter {

	@Autowired
	private RedisConfig redisConfig;

	@Bean
	public SpringJedisPoolFactoryBean springJedisPoolFactoryBean() {
		SpringJedisPoolFactoryBean sjb = new SpringJedisPoolFactoryBean();
		sjb.setServer(redisConfig.getServer());
		JedisPoolConfig jpcfg = new JedisPoolConfig();
		jpcfg.setMinEvictableIdleTimeMillis(redisConfig.getMinEvictableIdleTimeMillis());
		jpcfg.setMaxIdle(redisConfig.getMaxIdle());
		jpcfg.setMinIdle(redisConfig.getMinIdle());
		jpcfg.setMaxTotal(redisConfig.getMaxTotal());
		sjb.setPoolConfig(jpcfg);
		return sjb;
	}

	@Bean
	public JedisPoolResource jedisPoolResource(SpringJedisPoolFactoryBean springJedisPoolFactoryBean) {

		Pool<Jedis> pool = null;
		try {
			pool = springJedisPoolFactoryBean.getObject();
		} catch (Exception e) {

			GLog.error("get redis pool error:", e);
		}

		return new JedisPoolResource(pool);
	}

	@Bean
	@ConditionalOnMissingBean(BaseRedisCommand.class)
	public BaseRedisCommand baseRedisCommand(JedisPoolResource jedisPoolResource) {
		BaseRedisCommand brc = new BaseRedisCommand();
		brc.setRedisResource(jedisPoolResource);
		return brc;
	}
}
